package com.exam.api.config;

import cn.dev33.satoken.spring.SpringMVCUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.exam.api.common.utils.StpManagerUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {


    public void insertFill(MetaObject metaObject) {
        if (this.getFieldValByName("createTime", metaObject) == null) {
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }

        boolean web = SpringMVCUtil.isWeb();
        if (web) {
            boolean login = StpUtil.isLogin();
            if (this.getFieldValByName("createUserId", metaObject) == null && login) {
                this.setFieldValByName("createUserId", Long.parseLong(StpUtil.getLoginId(StpManagerUtil.getLoginId(""))), metaObject);
            }
        }

    }

    public void updateFill(MetaObject metaObject) {
        boolean web = SpringMVCUtil.isWeb();
        if (web) {
            boolean login = StpUtil.isLogin();
            if (this.getFieldValByName("updateUserId", metaObject) == null && login) {
                this.setFieldValByName("updateUserId", Long.parseLong(StpUtil.getLoginId(StpManagerUtil.getLoginId(""))), metaObject);
            }
        }
        if (this.getFieldValByName("updateTime", metaObject) == null) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
    }
}
